﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;

namespace YXChatApiService.ServiceCollectionExtension
{
    public static class ServiceCollectionDependencyExtension
    {
        /// <summary>
        /// 注入业务服务
        /// </summary>
        /// <param name="service"></param>
        /// <param name="dependencyType">注入的生命周期类型接口</param>
        public static void AddDependencyBusiness(this IServiceCollection service, Type dependencyType=null)
        {
            dependencyType ??=typeof(ITransientDependency);
            //获取继承了“注入接口”的所有类
            List<Type> types = AppDomain.CurrentDomain
                    .GetAssemblies()
                    .SelectMany(x => x.GetTypes())
                    .Where(t => t.IsClass && !t.IsAbstract
                                          && dependencyType.IsAssignableFrom(t)//判断类型是否实现了此接口,或继承的此类，或相同类型
                    )
                    .ToList();
            foreach (Type type in types)
            {
                //获取继承的接口
                Type[] interfaces = type.GetInterfaces();
                interfaces.ToList().ForEach(i =>
                {
                    //瞬时生命周期注入
                    if (dependencyType == typeof(ITransientDependency))
                    {
                        service.AddTransient(i, type);
                    }
                });
            }
        }
    }
}